package cn.com.connext.scrm.web.rest;

import cn.com.connext.scrm.cache.NoteCache;
import cn.com.connext.scrm.domain.enumeration.AuditStatus;
import cn.com.connext.scrm.domain.enumeration.DeleteStatus;
import cn.com.connext.scrm.domain.master.Note;
import cn.com.connext.scrm.repository.master.NoteCollectionRepository;
import cn.com.connext.scrm.repository.master.NoteLikesRepository;
import cn.com.connext.scrm.service.NoteService;
import cn.com.connext.scrm.service.dto.*;
import cn.com.connext.scrm.service.mapper.NoteMapper;
import cn.com.connext.scrm.web.rest.errors.MyErrorCode;
import cn.com.connext.scrm.web.rest.vm.*;
import com.codahale.metrics.annotation.Timed;
import com.connext.common.exception.ErrorCode;
import com.connext.common.exception.ServiceException;
import com.connext.common.web.rest.BaseResource;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.swing.text.html.parser.Entity;
import javax.validation.Valid;
import java.net.URISyntaxException;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeoutException;

/**
 * Created by YANG205 on 2018/6/27.
 */
@RestController
@RequestMapping("/api/note")
public class NoteResource extends BaseResource {
    private final Logger log = LoggerFactory.getLogger(NoteResource.class);

    @Autowired
    private NoteService noteService;

    @Autowired
    private NoteMapper noteMapper;

    @Autowired
    private NoteCollectionRepository noteCollectionRepository;

    @Autowired
    private NoteLikesRepository noteLikesRepository;

    @Autowired
    private NoteCache noteCache;

    public NoteResource() throws TimeoutException {
        super("Note");
    }

    /**
     * POST  /tasks : Create a new note.
     *
     * @param noteDTO the noteDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new noteDTO, or with status 400 (Bad Request) if the note has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/create")
    @Timed
    @ApiOperation(value = "创建笔记/问答（后台管理）", tags = {"帖子列表"}, notes = "创建笔记/问答（后台管理）")
    public ResponseEntity<NoteDTO> create(@Valid @RequestBody NoteDTO noteDTO) throws URISyntaxException {
        log.debug("REST request to save Note : {}", noteDTO);
        if (StringUtils.isNotEmpty(noteDTO.getId())) {
            throw new ServiceException(ErrorCode.ERROR_ID_EXISTS);
        }

        noteDTO.setCreateTime(ZonedDateTime.now());
        noteDTO.setAuditStatus(AuditStatus.UNAUDITED);
        noteDTO.setDeleteStatus(DeleteStatus.ACTIVATED);
        noteDTO.setIsTop(noteDTO.getIsTop() == null ? false : noteDTO.getIsTop());
        Note note = noteMapper.toEntity(noteDTO);
        NoteDTO result = noteService.saveNote(note);

        return createSuccess(result);
    }

    /**
     * GET  /getNoteInfo/:id : get the "id" note.
     *
     * @param id the id of the noteDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the noteDTO, or with status 404 (Not Found)
     */
    @Deprecated
    @GetMapping("/getNoteInfo/{id}/{unionId}")
    @Timed
    @ApiOperation(value = "获取帖子信息", tags = {"帖子列表"}, notes = "获取帖子信息")
    public ResponseEntity<NoteDTO> getNoteInfo(@PathVariable(value = "id") String id,
                                               @PathVariable(value = "unionId") String unionId) {
        log.debug("REST request to get Note : {}", id, unionId);
        if (StringUtils.isEmpty(id)) {
            throw new ServiceException(MyErrorCode.ERROR_ID_EMPTY);
        }
        if (StringUtils.isEmpty(unionId)) {
            throw new ServiceException(MyErrorCode.ERROR_UNIONID_EMPTY);
        }
        NoteDTO noteDTO = noteService.findOneDTO(id, unionId);
        return entityResponse(Optional.ofNullable(noteDTO));
    }

    @PostMapping("/getNoteInfo")
    @Timed
    @ApiOperation(value = "获取帖子信息", tags = {"帖子列表"}, notes = "获取帖子信息")
    public ResponseEntity<NoteDTO> getNoteInfo(@RequestBody NoteInfoVM vm) {
        log.debug("REST request to get Note : {}", vm.getId(), vm.getUnionId());
        if (StringUtils.isEmpty(vm.getId())) {
            throw new ServiceException(MyErrorCode.ERROR_ID_EMPTY);
        }
        if (StringUtils.isEmpty(vm.getUnionId())) {
            throw new ServiceException(MyErrorCode.ERROR_UNIONID_EMPTY);
        }
        NoteDTO noteDTO = noteService.findOneDTO(vm.getId(), vm.getUnionId());
        return entityResponse(Optional.ofNullable(noteDTO));
    }

    /**
     * DELETE  /delete/:id : delete the "id" note.
     *
     * @param id the id of the note to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/delete/{id}")
    @Timed
    @ApiOperation(value = "删除帖子", tags = {"帖子列表"}, notes = "删除帖子")
    public ResponseEntity deleteNote(@PathVariable String id) {
        log.debug("REST request to delete Note : {}", id);
        if (StringUtils.isEmpty(id)) {
            throw new ServiceException(ErrorCode.ERROR_ID_NOT_EXISTS);
        }
        noteService.deleteNote(id);
        return deleteSuccess();
    }

    /**
     * @param pageable
     * @param nickName
     * @param auditStatus
     * @param title
     * @return
     */
    @GetMapping("/noteList")
    @Timed
    @ApiOperation(value = "分页获取帖子列表（后台管理）", tags = {"帖子列表"}, notes = "分页获取帖子列表（后台管理）")
    public ResponseEntity<Page<NoteDTO>> getNoteList(@ApiParam Pageable pageable,
                                                     @RequestParam(required = false) String nickName,
                                                     @RequestParam(required = false) AuditStatus auditStatus,
                                                     @RequestParam(required = false) String title) {
        try {
            ///pageable   分页信息
            ///nickName   用户昵称
            ///auditStatus帖子审核状态
            ///title      帖子标题
            Page<NoteDTO> noteDTOPage = noteService.getAllUnDeletedNote(pageable, null, null, null, nickName, auditStatus, title);

            log.info("total:" + noteDTOPage.getTotalPages());
            log.info(noteDTOPage.toString());
            return pagedResponse(noteDTOPage);
        } catch (Exception e) {
            log.error("NoteResource->getNoteList:{}", e);
            return null;
        }
    }

    @GetMapping("/reviewNote/{id}")
    @Timed
    @ApiOperation(value = "审核帖子", tags = {"帖子列表"}, notes = "审核帖子")
    public Boolean reviewNote(@PathVariable String id) {
        log.debug("REST to review Note :{}", id);
        if (StringUtils.isEmpty(id)) {
            throw new ServiceException(MyErrorCode.ERROR_ID_EMPTY);
        }
        return noteService.reviewNote(id);
    }

    /**
     * @param pageable
     * @param keyWord
     * @param columnType
     * @param unionId
     * @return
     */
    @GetMapping("/noteListForWeChat")
    @Timed
    @ApiOperation(value = "分页获取帖子列表（小程序）", tags = {"帖子列表"}, notes = "分页获取帖子列表（小程序）")
    public ResponseEntity<Page<NoteDTO>> getNoteListForWeChat(@ApiParam Pageable pageable,
                                                              @RequestParam(required = false) String keyWord,
                                                              @RequestParam Integer columnType,
                                                              @RequestParam String unionId) {
        try {
            ///pageable   分页信息
            ///keyWord    暂定为搜索框内容
            ///columnType 暂定为分栏类型---0：全部，1：关注，2：品饮笔记，3：问答，4：DWA圈子
            ///unionId    用户的小程序UnionID
            Page<NoteDTO> noteDTOPage = noteService.getAllUnDeletedNote(pageable, keyWord, columnType, unionId, null, null, null);
            return pagedResponse(noteDTOPage);
        } catch (Exception e) {
            log.error("NoteResource->getNoteList:{}", e);
            return null;
        }
    }

    /**
     * @param lastIndex----上次获取最小index
     * @param size----pageSize
     * @param keyWord
     * @param columnType
     * @param unionId
     * @param isTop                    是否置顶
     * @return
     */
    @GetMapping("/noteListForWeChat2")
    @Timed
    @ApiOperation(value = "分页获取帖子列表（小程序）", tags = {"帖子列表"}, notes = "分页获取帖子列表（小程序）")
    public ResponseEntity<Page<NoteDTO>> getNoteListForWeChat2(@RequestParam Long lastIndex,
                                                               @RequestParam Integer size,
                                                               @RequestParam(required = false) String keyWord,
                                                               @RequestParam Integer columnType,
                                                               @RequestParam String unionId,
                                                               @RequestParam(required = false) Boolean isTop) {
        try {
            ///pageable   分页信息
            ///keyWord    暂定为搜索框内容
            ///columnType 暂定为分栏类型---0：全部，1：关注，2：品饮笔记，3：问答，4：DWA圈子
            ///unionId    用户的小程序UnionID
            if (isTop == null) {
                isTop = false;
            }
            log.info("分页获取帖子列表（小程序）lastIndex:" + lastIndex + "  isTop:" + (isTop ? "1" : false));
            Page<NoteDTO> noteDTOPage = noteService.getNotes4Wechat(lastIndex, size, keyWord, columnType, unionId, isTop);
            return pagedResponse(noteDTOPage);
        } catch (Exception e) {
            log.error("NoteResource->getNoteList:{}", e);
            return null;
        }
    }


    @PostMapping("/homeForWechat")
    @Timed
    @ApiOperation(value = "首页（小程序）", tags = {"帖子列表"}, notes = "首页（小程序）")
    public ResponseEntity homeForWechat(@RequestBody HomeVM vm){
        try{
            if (vm == null){
                return null;
            }
            log.info("获取首页列表,page:{}, isTop:{}",vm.getPage(), (vm.getTop() ? "1" : false));
            Page<NoteDTO> page = noteService.homeForWechat(vm);
            return pagedResponse(page);
        }catch (Exception e){
            log.error("获取首页失败:{}", e);
            return null;
        }
    }

    @PostMapping("/test")
    @Timed
    @ApiOperation(value = "首页缓存测试（小程序）", tags = {"帖子列表"}, notes = "首页缓存测试（小程序）")
    public ResponseEntity homeCacheTest(@RequestBody IndexVM vm){
        try{
            List<NoteDTO> result = new ArrayList<>();
            if (vm.getPage() == null){
                vm.setPage(0);
            }
            if (vm.getPageSize() == null){
                vm.setPageSize(5);
            }
            if (StringUtils.isNotEmpty(vm.getKeyword())){
                result = noteService.findKeyWordList(vm.getKeyword(), vm.getPage(), vm.getPageSize());
            }
            if (vm.getColumnType() == 0){
                result = noteService.findAllForHome(vm.getPage(), vm.getPageSize());
            }else if (vm.getColumnType() == 1){
                result = noteService.findUserFollow(vm.getUnionId(),vm.getPage(), vm.getPageSize());
            }else if (vm.getColumnType() == 2){
                result = noteService.findFineList(vm.getPage(), vm.getPageSize());
            }
            return entityResponse(result);
        }catch (Exception e){
            log.error("查询失败:{}", e);
            return null;
        }
    }

    @PostMapping("recommend")
    @Timed
    @ApiOperation(value = "推荐帖子", tags = {"帖子列表"}, notes = "推荐帖子")
    public ResponseEntity recommend(@RequestBody QueryIdVM vm){
        JsonResult result = new JsonResult();
        if (vm == null){
            return null;
        }
        try{
            noteService.recommend(vm);
            result.setState(0);
            result.setMessage("操作成功");
            return entityResponse(result);
        }catch (Exception e){
            log.error("推荐失败:{}", e);
            result.setState(1);
            result.setMessage("推荐失败");
            return entityResponse(result);
        }
    }


    @GetMapping("/recommendedNote")
    @Timed
    @ApiOperation(value = "获取推荐帖子", tags = {"帖子列表"}, notes = "获取推荐帖子")
    public ResponseEntity<Page<NoteDTO>> getRecommendedNote(@ApiParam Pageable pageable,
                                                            @RequestParam(required = false) String keyWord,
                                                            @RequestParam String unionId) {
        try {
            Page<NoteDTO> noteDTOPage = noteService.getRecommendedNotes(pageable, keyWord, unionId);
            return pagedResponse(noteDTOPage);
        } catch (Exception e) {
            log.error("NoteResource->getNoteList:{}", e);
            return null;
        }
    }


    @PostMapping("/createForWeChat")
    @Timed
    @ApiOperation(value = "创建笔记/问答（小程序）", tags = {"帖子列表"}, notes = "创建笔记/问答（小程序）")
    public JsonResult createForWeChat(@RequestBody NoteVM noteVM) {
        JsonResult jsonResult = new JsonResult();
        if (StringUtils.isEmpty(noteVM.getUserId()) || StringUtils.isEmpty(noteVM.getContent())){
            jsonResult.setMessage("请求参数缺失");
            jsonResult.setState(500);
            return jsonResult;
        }
        JsonResult result = noteService.saveNoteForWeChat(noteVM);

        return result;
    }

    @Deprecated
    @GetMapping("/getNoteInfoForWeChat")
    @Timed
    @ApiOperation(value = "获取帖子信息", tags = {"帖子列表"}, notes = "获取帖子信息")
    public ResponseEntity<NoteDTO> getNoteInfoForWeChat(@RequestParam String id,
                                                        @RequestParam String unionId) {
        log.debug("REST request to get Note : {}", id, unionId);
        if (StringUtils.isEmpty(id)) {
            throw new ServiceException(MyErrorCode.ERROR_ID_EMPTY);
        }
        if (StringUtils.isEmpty(unionId)) {
            throw new ServiceException(MyErrorCode.ERROR_UNIONID_EMPTY);
        }
        NoteDTO noteDTO = noteService.findOneDTOForWeChat(id, unionId);
        return entityResponse(Optional.ofNullable(noteDTO));
    }

    @PostMapping("/getNoteInfoForWeChat")
    @Timed
    @ApiOperation(value = "获取帖子信息", tags = {"帖子列表"}, notes = "获取帖子信息")
    public ResponseEntity<NoteDTO> getNoteInfoForWeChat(@RequestBody UnionIdNoteIdVM vm) {
        log.debug("REST request to get Note : {}", vm.getId(), vm.getUnionId());
        if (StringUtils.isEmpty(vm.getId())) {
            throw new ServiceException(MyErrorCode.ERROR_ID_EMPTY);
        }
        if (StringUtils.isEmpty(vm.getUnionId())) {
            throw new ServiceException(MyErrorCode.ERROR_UNIONID_EMPTY);
        }
        NoteDTO noteDTO = noteService.findOneDTOForWeChat(vm.getId(), vm.getUnionId());
        return entityResponse(Optional.ofNullable(noteDTO));
    }

    @Deprecated
    @GetMapping("/likeNote/{noteId}/{userId}")
    @Timed
    @ApiOperation(value = "帖子点赞/取消点赞", tags = {"帖子列表"}, notes = "帖子点赞/取消点赞")
    public JsonResult likeNote(@PathVariable(value = "noteId") String noteId,
                               @PathVariable(value = "userId") String userId) {
        log.debug("REST to like Note : {}", noteId, userId);
        if (StringUtils.isEmpty(noteId)) {
            throw new ServiceException(MyErrorCode.ERROR_NOTEID_EMPTY);
        }
        if (StringUtils.isEmpty(userId)) {
            throw new ServiceException(MyErrorCode.ERROR_USERID_EMPTY);
        }

        JsonResult res = new JsonResult();
        noteService.likeNote(noteId, userId);
        return res;
    }

    @PostMapping("/likeNote")
    @Timed
    @ApiOperation(value = "帖子点赞/取消点赞", tags = {"帖子列表"}, notes = "帖子点赞/取消点赞")
    public JsonResult likeNote(@RequestBody NoteIdUserIdVM vm) {
        JsonResult res = new JsonResult();
        try {
            log.debug("REST to like Note : {}", vm.getNoteId(), vm.getUserId());
            if (StringUtils.isEmpty(vm.getNoteId())) {
                throw new ServiceException(MyErrorCode.ERROR_NOTEID_EMPTY);
            }
            if (StringUtils.isEmpty(vm.getUserId())) {
                throw new ServiceException(MyErrorCode.ERROR_USERID_EMPTY);
            }
            noteService.likeNote(vm.getNoteId(), vm.getUserId());
            res.setMessage("点赞成功");
            res.setState(0);
            return res;
        }catch (Exception e){
            log.error("点赞失败:{}", e);
            res.setState(1);
            res.setMessage("点赞失败");
            return res;
        }
    }

    @PostMapping("/myAllLikeNote")
    @Timed
    @ApiOperation(value = "我所有点赞的帖子", tags = {"帖子列表"}, notes = "我所有点赞的帖子")
    public ResponseEntity myAllLikeNote(@RequestBody UserIdVM vm){
        try{
            if (vm == null){
                throw new ServiceException(MyErrorCode.ERROR_USERID_EMPTY);
            }
            List<String> list = noteLikesRepository.findNoteIdsByUserId(vm.getUserId());
            return entityResponse(list);
        }catch (Exception e){
            log.error("查询失败:{}", e);
            return null;
        }
    }

    @Deprecated
    @GetMapping("/collectNote/{noteId}/{userId}")
    @Timed
    @ApiOperation(value = "收藏帖子", tags = {"帖子列表"}, notes = "收藏帖子")
    public JsonResult collectNote(@PathVariable(value = "noteId") String noteId,
                                  @PathVariable(value = "userId") String userId) {
        log.debug("REST to collect Note : {}", noteId, userId);
        if (StringUtils.isEmpty(noteId)) {
            throw new ServiceException(MyErrorCode.ERROR_NOTEID_EMPTY);
        }
        if (StringUtils.isEmpty(userId)) {
            throw new ServiceException(MyErrorCode.ERROR_USERID_EMPTY);
        }

        JsonResult res = noteService.collectNote(noteId, userId);

        return res;
    }

    @PostMapping("/collectNote")
    @Timed
    @ApiOperation(value = "收藏帖子", tags = {"帖子列表"}, notes = "收藏帖子")
    public JsonResult collectNote(@RequestBody NoteIdUserIdVM vm) {
        log.debug("REST to collect Note : {}", vm.getNoteId(), vm.getUserId());
        if (StringUtils.isEmpty(vm.getNoteId())) {
            throw new ServiceException(MyErrorCode.ERROR_NOTEID_EMPTY);
        }
        if (StringUtils.isEmpty(vm.getUserId())) {
            throw new ServiceException(MyErrorCode.ERROR_USERID_EMPTY);
        }
        JsonResult res = noteService.collectNote(vm.getNoteId(), vm.getUserId());
        return res;
    }

//    @PostMapping("/repostNote")
//    @Timed
//    @ApiOperation(value = "转发帖子", tags = {"帖子列表"}, notes = "转发帖子")
//    public ResponseEntity<String> repostNote(@RequestParam String noteId,
//                                             @RequestParam String userId,
//                                             @RequestParam String authorId) throws URISyntaxException {
//        log.debug("REST to repost Note : {}", noteId, userId, authorId);
//        if (StringUtils.isEmpty(noteId)) {
//            throw new ServiceException(MyErrorCode.ERROR_NOTEID_EMPTY);
//        }
//        if (StringUtils.isEmpty(userId)) {
//            throw new ServiceException(MyErrorCode.ERROR_USERID_EMPTY);
//        }
//        if (StringUtils.isEmpty(authorId)) {
//            throw new ServiceException(MyErrorCode.ERROR_AUTHORID_EMPTY);
//        }
//
//        String res = noteService.repostNote(noteId, userId, authorId);
//
//        return createSuccess(res);
//    }

    @Deprecated
    @GetMapping("/browseNote/{noteId}/{userId}")
    @Timed
    @ApiOperation(value = "添加一条帖子浏览记录", tags = {"帖子列表"}, notes = "添加一条帖子浏览记录")
    public ResponseEntity<Boolean> createBrowseRecord(@PathVariable(value = "noteId") String noteId,
                                                      @PathVariable(value = "userId") String userId) throws URISyntaxException {

        log.debug("REST to browse Note : {}", userId, noteId);
        if (StringUtils.isEmpty(noteId)) {
            throw new ServiceException(MyErrorCode.ERROR_NOTEID_EMPTY);
        }
        if (StringUtils.isEmpty(userId)) {
            throw new ServiceException(MyErrorCode.ERROR_UNIONID_EMPTY);
        }

        Boolean res = noteService.browseNote(noteId, userId);

        return createSuccess(res);
    }

    @PostMapping("/browseNote")
    @Timed
    @ApiOperation(value = "添加一条帖子浏览记录", tags = {"帖子列表"}, notes = "添加一条帖子浏览记录")
    public ResponseEntity<Boolean> createBrowseRecord(@RequestBody NoteIdUserIdVM vm) throws URISyntaxException {

        log.debug("REST to browse Note : {}", vm.getUserId(), vm.getNoteId());
        if (StringUtils.isEmpty(vm.getNoteId())) {
            throw new ServiceException(MyErrorCode.ERROR_NOTEID_EMPTY);
        }
        if (StringUtils.isEmpty(vm.getUserId())) {
            throw new ServiceException(MyErrorCode.ERROR_UNIONID_EMPTY);
        }

        Boolean res = noteService.browseNote(vm.getNoteId(), vm.getUserId());

        return createSuccess(res);
    }

    @Deprecated
    @GetMapping("/myNoteList")
    @Timed
    @ApiOperation(value = "我的发布", tags = "帖子列表", notes = "我的发布")
    public ResponseEntity<Page<NoteDTO>> getNoteList(@ApiParam Pageable pageable,
                                                     @RequestParam String userId,
                                                     @RequestParam Integer noteType) {
        if (StringUtils.isEmpty(userId)) {
            throw new ServiceException(MyErrorCode.ERROR_USERID_EMPTY);
        }
        if (StringUtils.isEmpty(noteType.toString())) {
            throw new ServiceException(MyErrorCode.ERROR_NOTETYPE_EMPTY);
        }

        try {
            Page<NoteDTO> noteDTOPage = noteService.getMyNotes(pageable, userId, noteType);
            return pagedResponse(noteDTOPage);
        } catch (URISyntaxException e) {
            log.error("NoteResource->getMyAllNotes:{}", e);
            return null;
        }
    }

    @PostMapping("/myNoteList")
    @Timed
    @ApiOperation(value = "我的发布", tags = "帖子列表", notes = "我的发布")
    public ResponseEntity<Page<NoteDTO>> getNoteList(@RequestBody NoteListVM vm) {
        if (StringUtils.isEmpty(vm.getUserId())) {
            throw new ServiceException(MyErrorCode.ERROR_USERID_EMPTY);
        }
        if (StringUtils.isEmpty(vm.getNoteType().toString())) {
            throw new ServiceException(MyErrorCode.ERROR_NOTETYPE_EMPTY);
        }

        try {
            Page<NoteDTO> noteDTOPage = noteService.getMyNotes(new PageRequest(vm.getPage(), vm.getPageSize()), vm.getUserId(), vm.getNoteType());
            return pagedResponse(noteDTOPage);
        } catch (URISyntaxException e) {
            log.error("NoteResource->getMyAllNotes:{}", e);
            return null;
        }
    }

    @Deprecated
    @GetMapping("/myNoteCollection")
    @Timed
    @ApiOperation(value = "我的收藏", tags = "帖子列表", notes = "我的收藏")
    public ResponseEntity<Page<NoteDTO>> getMyAllNoteCollection(@ApiParam Pageable pageable,
                                                                @RequestParam String userId) {
        if (StringUtils.isEmpty(userId)) {
            throw new ServiceException(MyErrorCode.ERROR_USERID_EMPTY);
        }
        try {
            Page<NoteDTO> noteDTOPage = noteService.getMyNoteCollection(pageable, userId);
            return pagedResponse(noteDTOPage);
        } catch (URISyntaxException e) {
            log.error("NoteResource->getMyAllNotes:{}", e);
            return null;
        }
    }

    @PostMapping("/myNoteCollection")
    @Timed
    @ApiOperation(value = "我的收藏", tags = "帖子列表", notes = "我的收藏")
    public ResponseEntity<Page<NoteDTO>> getMyAllNoteCollection(@RequestBody CollectionListVM vm) {
        if (StringUtils.isEmpty(vm.getUserId())) {
            throw new ServiceException(MyErrorCode.ERROR_USERID_EMPTY);
        }
        try {
            Page<NoteDTO> noteDTOPage = noteService.getMyNoteCollection(new PageRequest(vm.getPage(), vm.getPageSize()), vm.getUserId());
            return pagedResponse(noteDTOPage);
        } catch (URISyntaxException e) {
            log.error("NoteResource->getMyAllNotes:{}", e);
            return null;
        }
    }

    @PostMapping("/myAllNoteCollection")
    @Timed
    @ApiOperation(value = "我所有的收藏", tags = "帖子列表", notes = "我所有的收藏")
    public ResponseEntity myAllNoteCollection(@RequestBody UserIdVM userIdVM){
        try{
            if (userIdVM == null){
                throw new ServiceException(MyErrorCode.ERROR_UNIONID_EMPTY);
            }
            List<String> list = noteCollectionRepository.findNoteIdByUserId(userIdVM.getUserId());
            return entityResponse(list);
        }catch (Exception e){
            log.info("查询出错:{}", e);
            return null;
        }
    }

    @Deprecated
    @GetMapping("/myAllNoteList")
    @Timed
    @ApiOperation(value = "我的所有帖子", tags = {"帖子列表"}, notes = "我的所有帖子")
    public ResponseEntity<Page<NoteDTO>> getAllNoteList(@ApiParam Pageable pageable,
                                                        @RequestParam String userId) {
        if (StringUtils.isEmpty(userId)) {
            throw new ServiceException(MyErrorCode.ERROR_USERID_EMPTY);
        }
        try {
            Page<NoteDTO> noteDTOPage = noteService.getMyAllNotes(pageable, userId);
            return pagedResponse(noteDTOPage);
        } catch (URISyntaxException e) {
            log.error("NoteResource->getMyAllNotes:{}", e);
            return null;
        }
    }

    @PostMapping("/myAllNoteList")
    @Timed
    @ApiOperation(value = "我的所有帖子", tags = {"帖子列表"}, notes = "我的所有帖子")
    public ResponseEntity<Page<NoteDTO>> getAllNoteList(@RequestBody CollectionListVM vm) {
        if (StringUtils.isEmpty(vm.getUserId())) {
            throw new ServiceException(MyErrorCode.ERROR_USERID_EMPTY);
        }
        try {
            Page<NoteDTO> noteDTOPage = noteService.getMyAllNotes(new PageRequest(vm.getPage(), vm.getPageSize()), vm.getUserId());
            return pagedResponse(noteDTOPage);
        } catch (URISyntaxException e) {
            log.error("NoteResource->getMyAllNotes:{}", e);
            return null;
        }
    }

    @GetMapping("/banNote/{noteId}")
    @Timed
    @ApiOperation(value = "封禁帖子", tags = {"帖子列表"}, notes = "封禁帖子")
    public String banNote(@PathVariable String noteId) {
        log.debug("REST to ban Note:{}", noteId);
        if (StringUtils.isEmpty(noteId)) {
            throw new ServiceException(MyErrorCode.ERROR_NOTEID_EMPTY);
        }

        return noteService.banNote(noteId);
    }

    @GetMapping("/unBanNote/{noteId}")
    @Timed
    @ApiOperation(value = "封禁帖子", tags = {"帖子列表"}, notes = "封禁帖子")
    public String unBanNote(@PathVariable String noteId) {
        log.debug("REST to unBan Note:{}", noteId);
        if (StringUtils.isEmpty(noteId)) {
            throw new ServiceException(MyErrorCode.ERROR_NOTEID_EMPTY);
        }

        return noteService.unBanNote(noteId);
    }

    @GetMapping("/getAllTags")
    @Timed
    @ApiOperation(value = "帖子标签", tags = {"帖子列表"}, notes = "获取所有帖子标签")
    public ResponseEntity getAllNoteTags() {
        return entityResponse(noteService.getAllNoteTags());
    }

    @GetMapping("/getRelevantComments/{wid}")
    @Timed
    @ApiOperation(value = "获取相关酒评论", tags = {"帖子列表"}, notes = "获取所有帖子标签")
    public ResponseEntity getNotesByWid(@PathVariable String wid) {

        return entityResponse(noteService.getNotesByWid(wid));

    }

    @PostMapping("/getCommentById")
    @Timed
    @ApiOperation(value = "获取相关酒评论根据酒品id", tags = {"帖子列表"}, notes = "获取所有帖子标签")
    public ResponseEntity getCommentById(@RequestBody GoodIdVM vm){
        return entityResponse(noteService.getCommentById(vm));
    }

    @PostMapping("/refreshAllCache")
    @Timed
    @ApiOperation(value = "刷新首页帖子缓存", tags = {"帖子列表"}, notes = "刷新首页帖子缓存")
    public ResponseEntity refreshCache() throws URISyntaxException {
        try {
            noteCache.refreshHomeCache();
            return createSuccess("ok");
        }catch (Exception e){
            log.info("刷新失败:{}", e);
            return null;
        }
    }


    @PostMapping("/refreshFineCache")
    @Timed
    @ApiOperation(value = "刷新首页帖子缓存", tags = {"帖子列表"}, notes = "刷新首页帖子缓存")
    public ResponseEntity refreshFineCache() throws URISyntaxException {
        try {
            noteCache.refreshFineCache();
            return createSuccess("ok");
        }catch (Exception e){
            log.info("刷新失败:{}", e);
            return null;
        }
    }

    @PostMapping("/refreshDetailCache")
    @Timed
    @ApiOperation(value = "刷新首页帖子缓存", tags = {"帖子列表"}, notes = "刷新首页帖子缓存")
    public ResponseEntity refreshDetailCache() throws URISyntaxException {
        try {
            noteCache.refreshDetailCache();
            return createSuccess("ok");
        }catch (Exception e){
            log.info("刷新失败:{}", e);
            return null;
        }
    }

    @GetMapping("testRedis")
    @Timed
    @ApiOperation(value = "测试redis", tags = {"帖子列表"}, notes = "测试redis")
    public String testRedis(@RequestParam String key){
        String result = noteService.testRedis(key);
        return result;
    }

    @PostMapping("isTop")
    @Timed
    @ApiOperation(value = "帖子置顶", tags = {"帖子列表"}, notes = "帖子置顶")
    public ResponseEntity isTop(@RequestBody QueryIdVM vm){
        JsonResult result = new JsonResult();
        try{
            if (vm == null){
                result.setMessage("参数错误");
                result.setState(1);
                return entityResponse(result);
            }
            noteService.isTop(vm);
            result.setState(0);
            result.setMessage("操作成功");
            return entityResponse(result);
        }catch (Exception e){
            log.error("置顶失败:{}", e);
            result.setState(1);
            result.setMessage("置顶失败");
            return entityResponse(result);
        }
    }

    @PostMapping("initSearchContent")
    @Timed
    @ApiOperation(value = "初始化帖子搜索内容", tags = {"帖子初始化"}, notes = "初始化帖子搜索内容")
    public ResponseEntity initSearchContent(){
        JsonResult result = new JsonResult();
        try{
            noteService.refreshSearchContent();
            result.setState(0);
            result.setMessage("操作成功");
            return entityResponse(result);
        }catch (Exception e){
            log.error("初始化失败:{}", e);
            result.setState(1);
            result.setMessage("初始化失败");
            return entityResponse(result);
        }
    }

    @PostMapping("changeIsRate")
    @Timed
    @ApiOperation(value = "帖子精选", tags = {"帖子列表"}, notes = "帖子精选")
    public ResponseEntity changeIsRate(@RequestBody QueryIdVM vm){
        JsonResult result = new JsonResult();
        try{
            noteService.changeIsRate(vm.getId());
            result.setState(0);
            result.setMessage("操作成功");
            return entityResponse(result);
        }catch (Exception e){
            log.error("操作失败:{}", e);
            result.setState(1);
            result.setMessage("操作失败");
            return entityResponse(result);
        }
    }
}
